package com.lili.other;

import java.util.HashMap;

/**
 * @Auther: 李 力
 * @Date: 2024/8/22
 * @Description: 146. LRU 缓存
 * @version: 1.0
 */
public class LRUCache {

    private HashMap<Integer, Node> map = new HashMap<>();

    private DTLinkedList list = new DTLinkedList();

    //容量
    private int capacity;

    public LRUCache(int capacity) {
        this.capacity = capacity;
    }

    public int get(int key) {
        if (!map.containsKey(key)) {
            return -1;
        }
        Node node = map.get(key);
        list.remove(node);
        list.addFirst(node);
        return node.value;
    }

    public void put(int key, int value) {
        if (map.containsKey(key)) {
            Node node = map.get(key);
            node.value = value;
            list.remove(node);
            list.addFirst(node);
        } else {
            Node node = new Node(key, value);
            map.put(key, node);
            list.addFirst(node);
            if (map.size() > capacity) {
                Node removed = list.removeLast();
                map.remove(removed.key);
            }
        }
    }

    static class Node {
        Node prev;
        Node next;
        int key;
        int value;

        public Node(int key, int value) {
            this.key = key;
            this.value = value;
        }

        public Node() {
        }
    }

    static class DTLinkedList {
        Node head;
        Node tail;

        public DTLinkedList() {
            head = tail = new Node();
            head.next = tail;
            tail.prev = head;
        }

        //头部添加
        public void addFirst(Node node) {
            Node first = head.next;
            node.prev = head;
            node.next = first;
            head.next = node;
            first.prev = node;
        }

        public Node removeLast() {
            Node last = tail.prev;
            remove(last);
            return last;
        }

        public void remove(Node node) {
            Node prev = node.prev;
            Node next = node.next;
            prev.next = next;
            next.prev = prev;
        }
    }


}
